package com.heifeng.cloudshelf.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.heifeng.cloudshelf.R;
import com.heifeng.cloudshelf.utils.ApkDownLoadUtils;
import com.heifeng.cloudshelf.utils.DensityUtils;
import com.heifeng.cloudshelf.utils.LogUtils;
import com.heifeng.cloudshelf.utils.NetCheck;
import com.heifeng.cloudshelf.utils.PhoneFormatCheckUtils;
import com.heifeng.cloudshelf.utils.ToastUitl;

import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Predicate;
import io.reactivex.subjects.PublishSubject;


/**
 * Created by admin on 2019/8/22.
 */

public class AppDialog extends Dialog {
    //    private static PublishSubject<Object> mStopCountingSubject;
//    private static Observable<Long> mCountDownObservable;
    private static boolean mCountToZero;
    private static boolean isNetConnected = false;
    private static TextView tvSendCode;
    private static Context mContext;
    private static boolean isStart = true;
    private static AppDialog dialog;
    private static long startTime = 0;

    public AppDialog(@NonNull Context context) {
        super(context);
    }

    private AppDialog(Context context, @LayoutRes int layoutRes, int width, int height) {
        super(context, R.style.AppDialog);
        mContext = context;
        // set content
        setContentView(layoutRes);

        Window window = getWindow();
        if (window != null) {

            WindowManager.LayoutParams params = window.getAttributes();
            if (width > 0) {
                params.width = width;
            } else {
                params.width = WindowManager.LayoutParams.WRAP_CONTENT;
            }
            if (height > 0) {
                params.height = height;
            } else {
                params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            }

            window.setAttributes(params);
        }
    }

    public static AppDialog TwoButtonDialog(Context context, String title, String content, String rightBtnText, String leftBtnText, final DoubleButtonOnClickListener listener) {
        closeDialog();
        dialog = new AppDialog(context, R.layout.layout_logout_dialog,
                DensityUtils.dp2px(context, 270), 0);
        dialog.setCanceledOnTouchOutside(false);

        TextView tvTitle = (TextView) dialog.findViewById(R.id.tv_title);
        TextView tvContent = (TextView) dialog.findViewById(R.id.tv_content);
        TextView btnLeft = (TextView) dialog.findViewById(R.id.btn_left);
        TextView btnRight = (TextView) dialog.findViewById(R.id.btn_right);

        tvTitle.setText(title);
        tvContent.setText(content);
        btnLeft.setText(leftBtnText);
        btnRight.setText(rightBtnText);

        btnLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (listener != null) {
                    listener.onLeftClick();
                }
            }
        });

        btnRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (listener != null) {
                    listener.onRightClick();
                }
            }
        });

        return dialog;
    }

    public static AppDialog OneButtonDialog(Context context, String title, String content, String btnText, final OneButtonOnClickListener listener) {
        closeDialog();
        dialog = new AppDialog(context, R.layout.layout_logout_dialog_one_btn,
                DensityUtils.dp2px(context, 270), 0);
        dialog.setCanceledOnTouchOutside(false);

        TextView tvTitle = (TextView) dialog.findViewById(R.id.tv_title);
        TextView tvContent = (TextView) dialog.findViewById(R.id.tv_content);
        TextView btn = (TextView) dialog.findViewById(R.id.tv_btn);

        tvTitle.setText(title);
        tvContent.setText(content);
        btn.setText(btnText);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (listener != null) {
                    listener.onBtnClick();
                }
            }
        });

        return dialog;
    }

    private static void closeDialog() {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        startTime = 0;
    }

    public static AppDialog LoginDialog(final Context context, boolean isNetConnect, final LoginOnClickListener listener) {
        closeDialog();
        if (isStart) {
            stopCountingSubject();
        }
        dialog = new AppDialog(context, R.layout.layout_login_dialog,
                DensityUtils.dp2px(context, 270), 0);
        dialog.setCanceledOnTouchOutside(false);
//        dialog.setCancelable(false);

        TextView btnGetCode = (TextView) dialog.findViewById(R.id.tv_get_code);
        TextView btn = (TextView) dialog.findViewById(R.id.tv_btn);
        TextView tvTimeTips = (TextView) dialog.findViewById(R.id.tv_time_over_tips);
        final TextView tvPhoneTips = (TextView) dialog.findViewById(R.id.tv_phone_tips);
        final TextView tvCodeTips = (TextView) dialog.findViewById(R.id.tv_code_tips);
        final ClearableEditText etPhone = (ClearableEditText) dialog.findViewById(R.id.et_phone);
        final ClearableEditText etCode = (ClearableEditText) dialog.findViewById(R.id.et_code);
        tvSendCode = btnGetCode;

        isNetConnected = isNetConnect;

        btnGetCode.setEnabled(false);
        btn.setEnabled(false);
        if (!isNetConnected) {
            tvTimeTips.setText("网络异常，请检查网络");
        }

        NetCheck instance = NetCheck.getInstance();
        int id = instance.setOnNetConnectListener(isConnect -> {
            isNetConnected = isConnect;
            if (!isConnect) {
                tvTimeTips.setText("网络异常，请检查网络");
            } else {
                tvTimeTips.setText("");
            }
        });

        btnGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isNetConnected) {
                    tvTimeTips.setText("网络异常，请检查网络");
                    ToastUitl.showLong("网络异常，请检查网络");
                    return;
                }

                if (0 != startTime && System.currentTimeMillis() - startTime < 1500) {
                    ToastUitl.showLong("操作过于频繁，请稍后！");
                    startTime = System.currentTimeMillis();
                    return;
                }

                if (TextUtils.isEmpty(etPhone.getText().toString().trim())) {
                    tvPhoneTips.setText(context.getResources().getString(R.string.text_phone_empty_tips));
                    tvPhoneTips.setVisibility(View.VISIBLE);
                    return;
                } else if (etPhone.getText().toString().trim().length() < 11 || !PhoneFormatCheckUtils.matchesPhoneNumber(etPhone.getText().toString().trim())) {
                    tvPhoneTips.setText(context.getResources().getString(R.string.text_phone_format_tips));
                    tvPhoneTips.setVisibility(View.VISIBLE);
                    return;
                }

                if (listener != null) {
//                    countTime();
                    listener.onCodeClick(etPhone.getText().toString().trim());
                    //dialog.dismiss();
                }
                etCode.requestFocus();//获取焦点 光标出现
            }
        });

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isNetConnected) {
                    tvTimeTips.setText("网络异常，请检查网络");
                    ToastUitl.showLong("网络异常，请检查网络");
                    return;
                }

                if (TextUtils.isEmpty(etPhone.getText().toString().trim()) && TextUtils.isEmpty(etCode.getText().toString().trim())) {
                    tvPhoneTips.setText(context.getResources().getString(R.string.text_phone_empty_tips));
                    tvCodeTips.setText(context.getResources().getString(R.string.text_code_empty_tips));
                    tvPhoneTips.setVisibility(View.VISIBLE);
                    tvCodeTips.setVisibility(View.VISIBLE);
                    return;
                } else if (TextUtils.isEmpty(etPhone.getText().toString().trim())) {
                    tvPhoneTips.setText(context.getResources().getString(R.string.text_phone_empty_tips));
                    tvPhoneTips.setVisibility(View.VISIBLE);
                    return;
                } else if (TextUtils.isEmpty(etCode.getText().toString().trim())) {
                    tvCodeTips.setText(context.getResources().getString(R.string.text_code_empty_tips));
                    tvCodeTips.setVisibility(View.VISIBLE);
                    return;
                } else if (etPhone.getText().toString().trim().length() < 11 || !PhoneFormatCheckUtils.matchesPhoneNumber(etPhone.getText().toString().trim())) {
                    tvPhoneTips.setText(context.getResources().getString(R.string.text_phone_format_tips));
                    tvPhoneTips.setVisibility(View.VISIBLE);
                    return;
                }
                if (listener != null) {
                    listener.onLoginClick(dialog, etPhone.getText().toString().trim(), etCode.getText().toString());
//                    stopCountingSubject();
//                    dialog.dismiss();
                }
            }
        });

        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0) {
                    tvPhoneTips.setVisibility(View.GONE);
                }

                if (editable.length() == 0) {
                    btnGetCode.setEnabled(false);
                    btnGetCode.setBackground(context.getResources().getDrawable(R.drawable.shape_d0d9e1_corner_6dp));
                    if (isStart) {
                        stopCountingSubject();
                    }
                } else {
                    btnGetCode.setEnabled(true);
                    btnGetCode.setBackground(context.getResources().getDrawable(R.drawable.shape_d6001d_corner_6dp));
                }

            }
        });

        etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0) {
                    tvCodeTips.setVisibility(View.GONE);
                }

                if (editable.length() == 0) {
                    btn.setEnabled(false);
                    btn.setBackground(context.getResources().getDrawable(R.drawable.shape_d0d9e1_corner_3dp));
                } else {
                    btn.setEnabled(true);
                    btn.setBackground(context.getResources().getDrawable(R.drawable.shape_d6001d_corner_3dp));
                }
            }
        });

        return dialog;
    }

    public static AppDialog AllowLocationDialog(Context context, final DoubleButtonOnEnquireClickListener listener) {
        closeDialog();
        dialog = new AppDialog(context, R.layout.layout_allow_location_dialog,
                DensityUtils.dp2px(context, 270), 0);
        dialog.setCanceledOnTouchOutside(false);

        TextView btnLeft = (TextView) dialog.findViewById(R.id.btn_left);
        TextView btnRight = (TextView) dialog.findViewById(R.id.btn_right);
        CheckBox cb_checkbox = dialog.findViewById(R.id.cb_checkbox);

        btnLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null)
                    listener.onLeftClick(cb_checkbox.isChecked());
                dialog.dismiss();
            }
        });

        btnRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null)
                    listener.onRightClick(cb_checkbox.isChecked());
                dialog.dismiss();
            }
        });

        return dialog;
    }

    public static AppDialog ProgressDialog(Context context, Activity activity, String title
            , String content, OnDownloadCompleteListener onDownloadCompleteListener) {
        closeDialog();
        dialog = new AppDialog(context, R.layout.layout_progress_dialog,
                DensityUtils.dp2px(context, 270), 0);
        dialog.setCanceledOnTouchOutside(false);

        TextView tvTitle = (TextView) dialog.findViewById(R.id.tv_title);
        TextView tvContent = (TextView) dialog.findViewById(R.id.tv_content);
        TextView btn = (TextView) dialog.findViewById(R.id.tv_btn);

        TextView tv_progress = (TextView) dialog.findViewById(R.id.tv_progress);

        ProgressBar progress = dialog.findViewById(R.id.progress);
        progress.setProgress(0);
        progress.setMax(100);

        new ApkDownLoadUtils(context, new ApkDownLoadUtils.OnDownLoadListener() {
            @Override
            public void onDownloadComplete(boolean isError) {
                activity.runOnUiThread(() -> {
                    tv_progress.setText("100%");
                });
                dialog.dismiss();
                if (null != onDownloadCompleteListener) {
                    onDownloadCompleteListener.onDownloadComplete(isError);
                }

            }

            @Override
            public void onDownloadProgress(long totalBytes, long currentBytes) {
                double s = (double) currentBytes / totalBytes * 100;
                String format;
                if (0 < s) {
                    format = new DecimalFormat("0.00").format(s);
                } else {
                    format = "0.00";
                }

                activity.runOnUiThread(() -> {
                    progress.setMax((int) totalBytes);
                    progress.setProgress((int) currentBytes);
                    tv_progress.setText(format);
                });

//                handler.post(() -> tv_progress.setText(format));

                LogUtils.e("format:" + format);
//                Message obtain = Message.obtain();
//                obtain.obj = format + "%";
//                obtain.what = 1;
//                handler.sendMessage(obtain);
            }
        }, tv_progress, progress).execute();
//        }).download();

        tvTitle.setText(title);
        tvContent.setText(content);


        return dialog;
    }

    public void showDialog() {
        if (isShowing()) {
            dismiss();
        }
        show();
    }


    public interface OnDownloadCompleteListener {
        void onDownloadComplete(boolean isError);
    }

    public interface DoubleButtonOnEnquireClickListener {
        void onLeftClick(boolean isEnquire);

        void onRightClick(boolean isEnquire);
    }

    public interface DoubleButtonOnClickListener {
        void onLeftClick();

        void onRightClick();
    }

    public interface OneButtonOnClickListener {
        void onBtnClick();
    }

    public interface LoginOnClickListener {
        void onCodeClick(String phone);

        void onLoginClick(AppDialog dialog, String phone, String code);
    }

    public static void stopCountingSubject() {
        isStart = false;
    }

    /**
     * 计时
     */
    public static void countTime(int time) {
        if (!isStart) {
            isStart = true;
        }
        PublishSubject<Object> stopCountingSubject = PublishSubject.create();
        Observable<Long> countDownObservable = Observable.interval(1, TimeUnit.SECONDS)
                .take(time)
                .takeWhile(new Predicate<Long>() {
                    @Override
                    public boolean test(Long aLong) throws Exception {
                        return isStart;
                    }
                })
                .takeUntil(stopCountingSubject)
                .observeOn(AndroidSchedulers.mainThread());
        countDownObservable.subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                tvSendCode.setEnabled(true);
                tvSendCode.setText(mContext.getString(R.string.text_get_code));
                tvSendCode.setBackground(mContext.getResources().getDrawable(R.drawable.shape_d6001d_corner_6dp));
            }

            @SuppressLint("StringFormatMatches")
            @Override
            public void onNext(Long aLong) {
                int countdown = time - 1 - aLong.intValue();
                mCountToZero = (countdown == 0);
                tvSendCode.setEnabled(false);
                tvSendCode.setText(mContext.getString(R.string.text_get_code_after, countdown));
                tvSendCode.setBackground(mContext.getResources().getDrawable(R.drawable.shape_dae2ea_corner_6dp));
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                tvSendCode.setEnabled(true);
                tvSendCode.setText(mContext.getString(R.string.text_get_code));
                tvSendCode.setBackground(mContext.getResources().getDrawable(R.drawable.shape_d6001d_corner_6dp));
            }
        });
    }
}
